package org.third.security.crypto;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

import java.security.Key;
import java.security.Security;

public class AesTest {
	public static final String KEY_ALGORITHM = "AES";
	public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

	public static byte[] initkey() throws Exception {

		// c 实例化密钥生成器
//      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//      KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM, "BC");
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		// c初始化 初始化密钥生成器，AES要求密钥长度为128位、192位、256位
//        kg.init(256); 
		kg.init(256);
		// A 生成密钥
		SecretKey secretKey = kg.generateKey();
		// A 获取二进制密钥编码形式
		return secretKey.getEncoded();
		// c 为了便于测试，这里我把key写死了，如果大家需要自动生成，可用上面注释掉的代码
//        return new byte[] { 0x08, 0x08, 0x04, 0x0b, 0x02, 0x0f, 0x0b, 0x0c,
//                0x01, 0x03, 0x09, 0x07, 0x0c, 0x03, 0x07, 0x0a, 0x04, 0x0f,
//                0x06, 0x0f, 0x0e, 0x09, 0x05, 0x01, 0x0a, 0x0a, 0x01, 0x09,
//                0x06, 0x07, 0x09, 0x0d };
	}

	public static byte[] encrypt(byte[] data, byte[] key, String ivStr) throws Exception {
		// c 还原密钥
//        Key k=toKey(key);
		Key k = null;
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
		//X 初始化，设置为加密模式
		IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes("utf-8"));
		cipher.init(Cipher.ENCRYPT_MODE, k, iv);
		//c 执行操作
		return cipher.doFinal(data);
	}

	public static void main(String[] args) throws Exception {
		initkey();
	}
}
